package com.gerryrun.lib_skin;

import android.app.Application;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.text.TextUtils;

import java.lang.reflect.Method;
import java.util.Observable;

public class SkinManager extends Observable {

    private final ApplicationActivityLifeCycle skinActivityLifeCycle;
    private Application mContext;
    private static SkinManager instance;

    public static SkinManager getInstance() {
        return instance;
    }

    public static SkinManager init(Application application) {
        if (instance == null) {
            synchronized (SkinManager.class) {
                if (instance == null) {
                    instance = new SkinManager(application);
                }
            }
        }
        return instance;
    }

    private SkinManager(Application mContext) {
        this.mContext = mContext;
        SkinResource.init(mContext);
        skinActivityLifeCycle = new ApplicationActivityLifeCycle(this);
        mContext.registerActivityLifecycleCallbacks(skinActivityLifeCycle);

        SkinPreference.init(mContext);
        SkinResource.init(mContext);
        ApplicationActivityLifeCycle activityLifeCycle = new ApplicationActivityLifeCycle(this);
        mContext.registerActivityLifecycleCallbacks(activityLifeCycle);
        loadSkin(SkinPreference.getInstance().getSkin());
    }

    public void loadSkin(String skinPath) {
        if (TextUtils.isEmpty(skinPath)) {
            SkinPreference.getInstance().reset();
            SkinResource.getInstance().reset();
        } else {
            try {
                //宿主app的 resources;
                Resources appResource = mContext.getResources();
//
                //反射创建AssetManager 与 Resource
                AssetManager assetManager = AssetManager.class.newInstance();
                //资源路径设置 目录或压缩包
                Method addAssetPath = assetManager.getClass().getMethod("addAssetPath",
                        String.class);
                addAssetPath.invoke(assetManager, skinPath);

                //根据当前的设备显示器信息 与 配置(横竖屏、语言等) 创建Resources
                Resources skinResource = new Resources(assetManager, appResource.getDisplayMetrics(),
                        appResource.getConfiguration());
                //获取外部Apk(皮肤包) 包名
                PackageManager mPm = mContext.getPackageManager();
                PackageInfo info = mPm.getPackageArchiveInfo(skinPath, PackageManager
                        .GET_ACTIVITIES);
                String packageName = info.packageName;
                SkinResource.getInstance().applySkin(skinResource, packageName);
                //记录
                SkinPreference.getInstance().setSkinPath(skinPath);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        setChanged();
        notifyObservers(null);
    }
}
